package com.excesys.exsecs.eco.service.impl;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.excesys.exsecs.eco.entity.EcoCoolHourFlow;
import com.excesys.exsecs.eco.entity.EcoPowerHourFlow;
import com.excesys.exsecs.eco.service.EcoCoolHourFlowService;
import com.excesys.exsecs.eco.service.EcoEfficiencyAnalyseService;
import com.excesys.exsecs.eco.service.EcoPowerHourFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.excesys.exsecs.eco.util.DateUtil;

@Service
public class EcoEfficiencyAnalyseServiceImpl implements EcoEfficiencyAnalyseService {
    //水量、流量
    @Autowired
    private EcoPowerHourFlowService ecoPowerHourFlowService;
    //冷量、流量
    @Autowired
    private EcoCoolHourFlowService ecoCoolHourFlowService;


    @Override
    public JSONObject getCopData(String startDate, String endDate) {
        //总能耗量 上期能耗量 环比增长率
        JSONObject jsonPower = new JSONObject();
        //日期时间字符串转换
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取数据库最新的时间格式 开始时间 与 结束时间
        //电
        Map newestTime = getNewestTime(startDate, endDate);
        //当日时间与当月时间
        String startTime = null;//起始时间
        String endTime = null;//结束时间
        //环比的时间
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        if (!newestTime.isEmpty()) {
            startDateTime = LocalDateTime.parse(newestTime.get("startTime").toString(), isoFormatter);
            startTime = startDateTime.format(customFormatter);
            endDateTime = LocalDateTime.parse(newestTime.get("endTime").toString(), isoFormatter);
            endTime = endDateTime.format(customFormatter);
        }
        //冷
        Map newestCoolTime = getNewestCoolTime(startDate, endDate);
        //当日时间与当月时间
        String startCoolTime = null;//起始时间
        String endCoolTime = null;//结束时间
        //环比的时间
        LocalDateTime startDateCoolTime = null;
        LocalDateTime endDateCoolTime = null;
        if (!newestCoolTime.isEmpty()) {
            startDateCoolTime = LocalDateTime.parse(newestCoolTime.get("startTime").toString(), isoFormatter);
            startCoolTime = startDateCoolTime.format(customFormatter);
            endDateCoolTime = LocalDateTime.parse(newestCoolTime.get("endTime").toString(), isoFormatter);
            endCoolTime = endDateCoolTime.format(customFormatter);
        }
        //日
        if (startDate.matches("\\d{4}-\\d{2}-\\d{2}") && endDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
            //获取左天的时间用来做判断用
            LocalDate today = LocalDate.now();
            // 判断开始时间和结束时间是否都在今天
            if (!startDate.equals(today.toString()) && !endDate.equals(today.toString())) {
                if (startDate.equals(endDate)) {
                    LocalDate days = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(1);
                    //获取开始时间与结束时间 用来做判断用 明天有没有数据, 没有数据则不进入
                    //电
                    Map newest = getNewestTime(days.toString(), days.toString());
                    if (!newest.isEmpty()) {
                        LocalDateTime nextDayDateTime = startDateTime.plusDays(1);
                        // 格式化并打印明天的日期时间
                        LocalDateTime dateTime1 = LocalDateTime.parse(nextDayDateTime.toString(), isoFormatter);
                        endTime = dateTime1.format(customFormatter);
                    }
                    //冷
                    Map newestCool = getNewestCoolTime(days.toString(), days.toString());
                    if (!newestCool.isEmpty()) {
                        LocalDateTime nextDayDateTime = startDateTime.plusDays(1);
                        // 格式化并打印明天的日期时间
                        LocalDateTime dateTime1 = LocalDateTime.parse(nextDayDateTime.toString(), isoFormatter);
                        endCoolTime = dateTime1.format(customFormatter);
                    }
                } else {
                    if (endTime != null) {
                        //区间查询，根据结束时间，获取明天的00:00:00点
                        endTime = LocalDateTime.parse(endTime, customFormatter).toLocalDate().plusDays(1).atStartOfDay().format(customFormatter);
                    }
                    if (endCoolTime != null) {
                        endCoolTime = LocalDateTime.parse(endCoolTime, customFormatter).toLocalDate().plusDays(1).atStartOfDay().format(customFormatter);
                    }
                }
            }
        }
        //电
        double sumPower = 0;
        if (startTime != null && endTime != null) {
            //能耗统计 - 反减
            double startSumPower = this.ecoPowerHourFlowService.getSumTotalPower(startTime);
            double endSumPower = this.ecoPowerHourFlowService.getSumTotalPower(endTime);
            if (startSumPower != 0 && endSumPower != 0) {
                sumPower = endSumPower - startSumPower;
            }
        }
        //总能耗量
        jsonPower.put("sumPower", new BigDecimal(sumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        double sumWhenPower = 0.0;
        if (startTime != null && endTime != null) {
            long hours = java.time.Duration.between(LocalDateTime.parse(startTime, customFormatter), LocalDateTime.parse(endTime, customFormatter)).toHours();
            sumWhenPower = new BigDecimal(sumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() / hours;
        }
        jsonPower.put("sumWhenPower", new BigDecimal(sumWhenPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        //冷
        double sumCool = 0;
        if (startTime != null && endTime != null) {
            //能耗统计 - 反减
            double startSumCool = this.ecoCoolHourFlowService.getSumTotalCool(startTime);
            double endSumCool = this.ecoCoolHourFlowService.getSumTotalCool(endTime);
            if (startSumCool != 0 && endSumCool != 0) {
                sumCool = endSumCool - startSumCool;
            }
        }
        jsonPower.put("sumCool", new BigDecimal(sumCool).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        double sumWhenCool = 0.0;
        if (startTime != null && endTime != null) {
            long coolHours = java.time.Duration.between(LocalDateTime.parse(startTime, customFormatter), LocalDateTime.parse(endTime, customFormatter)).toHours();
            sumWhenCool = new BigDecimal(sumCool).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() / coolHours;
        }
        jsonPower.put("sumWhenCool", new BigDecimal(sumWhenCool).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        //cop
        double sumCop = 0;
        if (startTime != null && endTime != null) {
            //能耗统计 - 反减
            double startSumCop = this.ecoCoolHourFlowService.getSumTotalCop(startTime);
            double endSumCop = this.ecoCoolHourFlowService.getSumTotalCop(endTime);
            if (startSumCop != 0 && endSumCop != 0) {
                sumCop = endSumCop - startSumCop;
            }
        }
        jsonPower.put("sumCop", new BigDecimal(sumCop).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return jsonPower;
    }


    @Override
    public JSONObject getCopList(String startTime, String endTime) {
        JSONObject jsonPower = new JSONObject();
        //图层时间
        String layerStartTime;
        String layerEndTime;
        List<Map<String, Object>> ctherCoolList ; //冷
        List<Map<String, Object>> chartPowerList;//电
        List<Map<String, Object>> ctherCoolCopList; //Cop

        // Create图层时间
        layerStartTime = startTime + " 01";//开始时间
        // 解析给定的日期字符串
        LocalDate givenDate = LocalDate.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        // 获取明天的日期
        LocalDate nextDay = givenDate.plusDays(1);
        layerEndTime = nextDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00";
        /* 图表 */
        //最新数据
        //电
        chartPowerList = this.ecoPowerHourFlowService.chartPower(layerStartTime, layerEndTime);
        //冷
        ctherCoolList = ecoCoolHourFlowService.chartPower(layerStartTime, layerEndTime);
        //Cop
        ctherCoolCopList = ecoCoolHourFlowService.chartPowerCop(layerStartTime, layerEndTime);
        List<Map<String, Object>> mapList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<LocalDateTime> list = DateUtil.getDateBetween(LocalDateTime.parse(startTime + " 01:00:00", formatter), LocalDateTime.parse(nextDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00", formatter));
        for (LocalDateTime localDateTime : list) {
            String strHour = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> map = new HashMap<>();
            map.put("hour", strHour);
            //电
            if (!chartPowerList.isEmpty()) {
                List<Map<String, Object>> yearData = chartPowerList.stream().filter(bo -> bo.get("timeValue").equals(localDateTime))
                        .collect(Collectors.toList());
                if (yearData != null && yearData.size() > 0) {
                    Double powerData = Double.parseDouble(yearData.get(0).get("totalValue").toString());
                    map.put("power", powerData);
                } else {
                    map.put("power", 0);
                }
            }
            //冷
            if (!ctherCoolList.isEmpty()) {
                List<Map<String, Object>> coolYearData = ctherCoolList.stream().filter(bo -> bo.get("timeValue").equals(localDateTime))
                        .collect(Collectors.toList());
                if (coolYearData != null && coolYearData.size() > 0) {
                    Double CoolData = Double.parseDouble(coolYearData.get(0).get("totalValue").toString());
                    map.put("cool", CoolData);
                } else {
                    map.put("cool", 0);
                }
            }
            //cop
            if (!ctherCoolCopList.isEmpty()) {
                List<Map<String, Object>> coolCopData = ctherCoolCopList.stream().filter(bo -> bo.get("timeValue").equals(localDateTime))
                        .collect(Collectors.toList());
                if (coolCopData != null && coolCopData.size() > 0) {
                    Double otherCopData = Double.parseDouble(coolCopData.get(0).get("totalValue").toString());
                    map.put("cop", new BigDecimal(otherCopData).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    map.put("cop", 0);
                }
            }
            mapList.add(map);
        }
        jsonPower.put("tableData", mapList);//表格
        return jsonPower;
    }

    //电
    public Map getNewestTime(String startDate, String endDate) {
        Map map = new HashMap();
        //获取当前时间
        EcoPowerHourFlow startHourFlow = this.ecoPowerHourFlowService.getBaseMapper().selectOne(Wrappers.<EcoPowerHourFlow>lambdaQuery()
                .like(EcoPowerHourFlow::getTimeValue, startDate)
                .orderByAsc(EcoPowerHourFlow::getTimeValue).last("LIMIT 1"));
        //获取上一条数据
        EcoPowerHourFlow endHourFlow = this.ecoPowerHourFlowService.getBaseMapper().selectOne(Wrappers.<EcoPowerHourFlow>lambdaQuery()
                .like(EcoPowerHourFlow::getTimeValue, endDate)
                .orderByDesc(EcoPowerHourFlow::getTimeValue).last("LIMIT 1"));
        if (ObjectUtils.isNotEmpty(startHourFlow) && ObjectUtils.isNotEmpty(endHourFlow)) {
            map.put("startTime", startHourFlow.getTimeValue().toString());
            map.put("endTime", endHourFlow.getTimeValue().toString());
        }
        return map;
    }

    //冷
    public Map getNewestCoolTime(String startDate, String endDate) {
        Map map = new HashMap();
        //获取当前时间
        EcoCoolHourFlow startHourFlow = this.ecoCoolHourFlowService.getBaseMapper().selectOne(Wrappers.<EcoCoolHourFlow>lambdaQuery()
                .like(EcoCoolHourFlow::getTimeValue, startDate)
                .orderByAsc(EcoCoolHourFlow::getTimeValue).last("LIMIT 1"));
        //获取上一条数据
        EcoCoolHourFlow endHourFlow = this.ecoCoolHourFlowService.getBaseMapper().selectOne(Wrappers.<EcoCoolHourFlow>lambdaQuery()
                .like(EcoCoolHourFlow::getTimeValue, endDate)
                .orderByDesc(EcoCoolHourFlow::getTimeValue).last("LIMIT 1"));
        if (ObjectUtils.isNotEmpty(startHourFlow) && ObjectUtils.isNotEmpty(endHourFlow)) {
            map.put("startTime", startHourFlow.getTimeValue().toString());
            map.put("endTime", endHourFlow.getTimeValue().toString());
        }
        return map;
    }
}
